package com.cw.jeeyt.controller.security;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.ResultData;
import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.pojo.TreeNode;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.security.SecurityResourceBo;
import com.cw.jeeyt.service.bo.security.SecurityUserBo;
import com.cw.jeeyt.core.util.SessionUtil;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.jeeyt.service.intf.security.SecurityResourceService;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.common.utils.GsonUtil;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * 资源信息控制层
 *
  * @author chenw
 * @version 1.0.0
 */
@Controller
@RequestMapping("/securityResource")
public class SecurityResourceController extends BaseController {
    @Resource
    private SecurityResourceService securityResourceService;

    /**
     * 跳转到资源信息列表查询页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/index")
    public ModelAndView query() throws Exception {
        ModelAndView mv = new ModelAndView("security/securityResource_index");
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listResource")
    public ResultData listResource(@RequestBody DataTable dataTable) throws Exception {

        SecurityResourceBo resourceBo = JSONObject.parseObject(JSON.toJSONString(dataTable.getQueryCond()),
            SecurityResourceBo.class);
        if (resourceBo == null) {
            resourceBo = new SecurityResourceBo();
        }
        PageInfo<SecurityResourceBo> pageInfo = securityResourceService.queryByPage(resourceBo, dataTable.getStart(),
            dataTable.getLength());
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到资源信息表单页面
     *
     * @param id 主键
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-form")
    public ModelAndView editForm(Long id, String operation) throws Exception {

        ModelAndView mv = new ModelAndView("security/securityResource_form");
        SecurityResourceBo resourceBo = null;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            resourceBo = new SecurityResourceBo();
        } else {
            resourceBo = securityResourceService.getResourceById(id);
        }
        mv.addObject("securityResource", resourceBo);
        mv.addObject("operation", operation);
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 根据操作类型保存资源信息数据
     *
     * @param resourceBo
     * @param operation add 新增  edit 修改
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/saveResource", method = RequestMethod.POST)
    public JsonResultDto saveResource(SecurityResourceBo resourceBo, String operation) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            if (operation.equals(EnumOperateFlag.ADD.getCode())) {
                securityResourceService.saveSecurityResource(resourceBo);
            } else if (operation.equals(EnumOperateFlag.EDIT.getCode())) {
                securityResourceService.updateSecurityResource(resourceBo);
            }
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("保存失败:" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 根据操作类型保存资源信息数据
     *
     * @param resourceJson
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/asyncResource", method = RequestMethod.POST)
    public JsonResultDto asyncResource(String resourceJson) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            securityResourceService.asyncResource(resourceJson);
            jsonResultDto.setMsg("同步成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("同步失败:" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 刷新菜单缓存
     */
    @ResponseBody
    @RequestMapping(value = "/refreshResource", method = RequestMethod.POST)
    public JsonResultDto refreshResource() {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            securityResourceService.refreshResource();
            jsonResultDto.setMsg("刷新成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("同步失败:" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 删除资源信息
     *
     * @param resourceBo
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public JsonResultDto delete(SecurityResourceBo resourceBo) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            securityResourceService.delete(resourceBo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("删除失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 跳转到系统后台管理首页
     *
     * @param request
     * @return
     */
    @RequestMapping("/initMenu")
    @ResponseBody
    public JsonResultDto initMenu(HttpServletRequest request) {
        JsonResultDto jsonResultDto = new JsonResultDto(false);
        SecurityUserBo userVo = SessionUtil.getSessionUser();
        String menuInfo = null;
        try {
            Long userId = userVo.getId();
            menuInfo = securityResourceService.queryResourceByLoginUser(userId, request);
            jsonResultDto.setData(menuInfo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg(e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 根据操作类型保存系统菜单表数据
     *
     * @param id
     * @param parentId add 新增  edit 修改
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/updateResourceParentId", method = RequestMethod.POST)
    public JsonResultDto updateResourceParentId(Long id, Long parentId) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            securityResourceService.updateResourceParentId(id, parentId);
            jsonResultDto.setMsg("更新成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("更新失败:" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 删除系统菜单表
     *
     * @param id
     * @throws Exception
     */
    @RequestMapping(value = "/updateResName")
    @ResponseBody
    public JsonResultDto updateResName(Long id, String resName) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            securityResourceService.updateResourceName(id, resName);
            jsonResultDto.setSuccess(true);
            jsonResultDto.setMsg("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("更新失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 根据节点id加载叶子节点
     *
     * @param parentId
     * @return
     */
    @RequestMapping("/getNodesDataById")
    @ResponseBody
    public String getNodesDataById(Long parentId) throws Exception {
        List<SecurityResourceBo> securityResourceList = securityResourceService.querySecurityResourceListByParentId(
            parentId);
        List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
        if (securityResourceList != null && !securityResourceList.isEmpty()) {
            for (SecurityResourceBo securityResource : securityResourceList) {
                TreeNode treeNode = new TreeNode();
                treeNode.setId(securityResource.getId());
                treeNode.setpId(securityResource.getParentId());
                treeNode.setName(securityResource.getResName());
                treeNode.setIsMenu(securityResource.getIsMenu());
                treeNode.setOpen(false);
                treeNodeList.add(treeNode);
            }
        }
        return GsonUtil.objectToJsonString(treeNodeList);
    }

    /**
     * 跳转到资源树页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/resource_tree")
    public ModelAndView menuTree() throws Exception {

        ModelAndView mv = new ModelAndView("security/securityResource_tree");
        //加载根节点菜单信息
        SecurityResourceBo securityResourceBo = securityResourceService.queryRootSecurityResource();
        String nodesJson = "";
        if (securityResourceBo != null) {
            nodesJson = securityResourceService.queryResourceJson(securityResourceBo.getId(), true, false);
        }
        if (!StringUtils.isEmpty(nodesJson)) {
            nodesJson = nodesJson.replace("\"", "'");
        }
        mv.addObject("nodesJson", nodesJson);
        return mv;
    }

    /**
     * 跳转到选择系统资源
     *
     * @param id 菜单id
     * @return
     */
    @RequestMapping(value = "/selectParentResource")
    public ModelAndView selectParentMenu(String id,String returnMethod,String selectType) {

        ModelAndView mv = new ModelAndView("security/securityResource_selectIndex");
        mv.addObject("returnMethod",returnMethod);
        mv.addObject("selectType",selectType);
        mv.addObject("id", id);
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @param id 菜单id
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listSelectSecurityResource")
    public ResultData listParentSecurityResource(@RequestBody DataTable dataTable, Long id) throws Exception {

        SecurityResourceBo securityResourceBo = JSONObject.parseObject(JSON.toJSONString(dataTable.getQueryCond()),
            SecurityResourceBo.class);
        if (securityResourceBo == null) {
            securityResourceBo = new SecurityResourceBo();
        }
        securityResourceBo.setId(id);
        PageInfo<SecurityResourceBo> pageInfo = securityResourceService.querySelectSecurityResource(securityResourceBo,
            dataTable.getStart(), dataTable.getLength());
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }
}
